package com.example.phone;

import com.example.entity.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.MybatisUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;

@WebServlet("/bindPhone")
public class BindPhoneServlet extends HttpServlet {
    private UserService service;
    private SqlSession sqlSession;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new UserServiceImpl(sqlSession);
    }

    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User) request.getSession().getAttribute("user");

        // 设置编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        HttpSession session = request.getSession();
        String phone = request.getParameter("phone");

        if (phone == null || phone.isEmpty()) {
            response.getWriter().write("{\"success\":false,\"message\":\"手机号不能为空\"}");
            return;
        }

        try {
            // 1. 检查手机号是否已被其他用户绑定
            if (service.isExistByPhone(phone) > 0) {
                response.getWriter().write("{\"success\":false,\"message\":\"该手机号已被其他用户绑定\"}");
                return;
            }

            // 2. 更新当前用户的手机号
//            int updateResult = service.updatePhone(user.getU_id(), phone);
//
//            if (updateResult > 0) {
//                service.commit();
//                // 3. 更新成功，清除验证码并返回成功响应
//                session.removeAttribute("phone_code");
//                response.getWriter().write("{\"success\":true,\"message\":\"绑定成功\"}");
//            } else {
//                // 4. 更新失败
//                response.getWriter().write("{\"success\":false,\"message\":\"绑定失败，请重试\"}");
//            }

        } catch (Exception e) {
            e.printStackTrace();
            service.rollback();
            response.getWriter().write("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        }
    }
}
